package com.jx.servlet;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.jx.dao.StudentDao;
import com.jx.entity.Student;
import com.jx.util.PageResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@WebServlet("/student")
public class StudentServlet extends HttpServlet { // 修复：继承 HttpServlet
    private StudentDao studentDao;

    @Override
    public void init() throws ServletException {
        studentDao = new StudentDao();
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        // 1. 获取请求参数cmd（区分前端的不同操作）
        String cmd = req.getParameter("cmd");
        // 2. 根据cmd的值，调用不同的方法处理不同的业务逻辑
        if (StrUtil.isNotBlank(cmd)) { // 相当于：cmd != null && cmd.trim().length() > 0
            if ("list".equals(cmd)) {   // 查询所有学生
                list(req,resp);
            }
            if("findByPage".equals(cmd)) {
                findByPage(req,resp);
            }
        }
    }

    // 分页查询
    private void findByPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 获取分页参数
        int page = Integer.parseInt(req.getParameter("page"));
        int pageSize = Integer.parseInt(req.getParameter("pageSize"));
        PageResult<Student> pageResult = studentDao.findByPage(page,pageSize);
        String json = JSONUtil.toJsonStr(pageResult);
        resp.getWriter().write(json);
        resp.getWriter().flush();
    }

    // 列表学生
    private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 查询所有学生
        List<Student> students = studentDao.findAll();
        // 2. 转换为json字符串并送到前端
        String json = JSONUtil.toJsonStr(students);
        resp.getWriter().write(json);
        resp.getWriter().flush();
    }
}